/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: SpringUtil
 * @Package com.rx.core.util
 * @Description: 获取spring上下文工具类
 * @author: 陈锦韬
 * @date: 2020\4\18 0018
 * @version V1.0
 * @Copyright: 2020 陈锦韬  All rights reserved.
 */
package com.rx.core.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: Administrator
 * @Description: 获取spring上下文工具类
 * @date: 2020\4\18 0018
 */
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        log.info("\n\n======================================================\n*\n*  开启您的奇迹\n*\n======================================================\n");
    }

    //获取applicationContext
    public static ApplicationContext getContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getContext().getBean(clazz);
    }

    public static <T> List<T> getBeanList(Class<T> clazz){
        List<T> result = Lists.newArrayList();
        Map<String, T> map =  getContext().getBeansOfType(clazz);
        if(EmptyChecker.isEmpty(map)){
            return result;
        }
        for(Map.Entry<String,T> entry:map.entrySet()){
            result.add(entry.getValue());
        }

        return result;
    }
/*    public static <T> List<T> getBean(Class<T> clazz){
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        return applicationContext.getBeansOfType(clazz);
    }*/
    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getContext().getBean(name, clazz);
    }

}
